package com.jiyongjun.bms.tool.dto;

import com.jiyongjun.bms.tool.exception.BizException;
import com.jiyongjun.bms.tool.exception.ServiceException;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * <h2>ajax请求返回结果封装</h2>
 * description:
 *
 * @author yongjun.ji
 * @since 1.0 2019/5/27
 */
@Data
@Slf4j
@Accessors(chain = true)
public class Result<T> implements Serializable {
    /** 成功 */
    public static final int CODE_SUCCESS = 0;
    /** 业务异常 */
    public static final int CODE_BIZ_EXCEPTION = -1;
    /** 服务异常 */
    public static final int CODE_SERVICE_EXCEPTION = -2;

    private Integer code;
    private String message;
    private T re;

    public static <R> Result<R> success(R re) {
        return new Result<R>()
                .setCode(CODE_SUCCESS)
                .setRe(re);
    }

    public static <R> Result<R> bizFailed(BizException e) {
        return bizFailed(e.getMessage());
    }

    public static <R> Result<R> bizFailed(String message) {
        log.warn("业务异常信息：{}", message);
        return new Result<R>()
                .setCode(CODE_BIZ_EXCEPTION)
                .setMessage(message);
    }

    public static <R> Result<R> serviceFailed(ServiceException e) {
        log.error("业务异常信息：{}", e.getMessage(), e);
        return new Result<R>()
                .setCode(CODE_SERVICE_EXCEPTION)
                .setMessage("服务器繁忙，请稍候重试......");
    }

    public static <R> Result<R> serviceFailed(Exception e) {
        log.error("业务异常信息：{}", e.getMessage(), e);
        return new Result<R>()
                .setCode(CODE_SERVICE_EXCEPTION)
                .setMessage("服务器繁忙，请稍候重试......");
    }
}
